<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-01-30 11:05:44
 * @Last Modified time: 2023-02-13 16:04:06
 */

namespace app\api\middleware;


use app\Request;
use frank\constants\StatusCode;
use frank\middleware\MiddlewareInterface;
use think\facade\Config;
use frank\exception\CommonException;
use frank\exception\AuthException;
use app\common\services\user\UserAuthService;
use frank\utils\helper\StringHelper;
/**
 * Class AuthMiddleware
 * @package app\api\middleware
 */
class AuthMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, \Closure $next)
    {
        $annotate = $request->annotate();
        $force = $annotate['force'][0] ?? true;
        $authInfo = null;
        $authori = $request->header('Authori-zation') ?? '';
        $token = trim(ltrim($authori, 'Bearer'));
        try {
            $authInfo = UserAuthService::instance()->parseToken($token);
        } catch (AuthException $e) {
            if (StringHelper::isTrue($force))
            	throw new CommonException($e->getMessage(),$e->getCode());
        }


        if (!is_null($authInfo)) {
            Request::macro('user', function (string $key = null) use (&$authInfo) {
                if ($key) {
                    return $authInfo['user'][$key] ?? '';
                }
                return $authInfo['user'];
            });
            Request::macro('tokenData', function () use (&$authInfo) {
                return $authInfo['tokenData'];
            });
        }
        Request::macro('isLogin', function () use (&$authInfo) {
            return !is_null($authInfo);
        });
        Request::macro('uid', function () use (&$authInfo) {
            return is_null($authInfo) ? 0 : (int)$authInfo['user']['id'];
        });
        return $next($request);
    }
}
